﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DTO;

namespace DAO
{

	public class NewsDAO:IData 
 	{
		public NewsDAO(String myconnecString) : base(myconnecString) { }

		public  int OnSubmit(News item, int t) {
			 return connec.ExecuteNonQuery("sp_News", CommandType.StoredProcedure,new SqlParameter("@flag", t),
				 new SqlParameter("@" + News.c_idNew, item.idNew), new SqlParameter("@" + News.c_idCat, item.idCat),
				 new SqlParameter("@" + News.c_addedDate, item.addedDate), new SqlParameter("@" + News.c_imageNew, item.imageNew),
				 new SqlParameter("@" + News.c_orderId, item.orderId), new SqlParameter("@" + News.c_title, item.title),
				 new SqlParameter("@" + News.c_Description, item.Description), new SqlParameter("@" + News.c_bodyNew, item.bodyNew),
				 new SqlParameter("@" + News.c_isTindacbiet, item.isTindacbiet), new SqlParameter("@" + News.c_GroupID, item.GroupID),
				 new SqlParameter("@" + News.c_isAuto, item.isAuto), new SqlParameter("@" + News.c_isActive, item.isActive)); 
		}

		public  News GetItem(IDataReader dr)
		{
			News obj = new News();
			obj.idNew = Convert.ToInt64(dr[News.c_idNew]);
			obj.idCat = Convert.ToInt32(dr[News.c_idCat]);
			obj.addedDate = Convert.ToDateTime(dr[News.c_addedDate]);
			obj.imageNew = Convert.ToString(dr[News.c_imageNew]);
			obj.orderId = Convert.ToInt32(dr[News.c_orderId]);
			obj.title = Convert.ToString(dr[News.c_title]);
			obj.Description = Convert.ToString(dr[News.c_Description]);
			obj.bodyNew = Convert.ToString(dr[News.c_bodyNew]);
			obj.isTindacbiet = Convert.ToBoolean(dr[News.c_isTindacbiet]);
			obj.GroupID = Convert.ToInt32(dr[News.c_GroupID]);
			obj.isAuto = Convert.ToBoolean(dr[News.c_isAuto]);
			obj.isActive = Convert.ToInt32(dr[News.c_isActive]);
			return obj;
		}

		public  List<News> GetAll()
		{
			return GetAll("select * from " + News.b_News, CommandType.Text);
		}

        private List<News> GetAll(String strSQL, CommandType commandtype)
        {
            List<News> list = new List<News>();
            SqlConnection connection = connec.Connection;
            SqlCommand command = new SqlCommand();
            command.CommandType = commandtype;
            command.CommandText = strSQL;
            command.Connection = connection;
            connection.Open();
            SqlDataReader reader;
            using (reader = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    list.Insert(0, GetItem(reader));
                }
                reader.Close();
            }
            connection.Close();
            return list;
        }
		public  News GetItemById(object id)
		{
			 return this.GetAll().FirstOrDefault(x => x.idNew == Convert.ToInt64(id));
		} 

	}

 }
